package com.zdkj.subway.support.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zdkj.common.core.util.R;
import com.zdkj.common.log.annotation.SysLog;
import com.zdkj.common.security.service.PigxUser;
import com.zdkj.common.security.util.ObjectUtils;
import com.zdkj.common.security.util.SecurityUtils;
import com.zdkj.subway.support.dto.in.SwPmLongPeriodSettlementDTO;
import com.zdkj.subway.support.entity.SwPmLongPeriodSettlement;
import com.zdkj.subway.support.service.SwPmLongPeriodSettlementService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;


/**
 * 长周期结算日期参数表
 *
 * @author cuilei
 * @date 2020-05-29 16:57:41
 */
@RestController
@AllArgsConstructor
@RequestMapping("/swpmlongperiodsettlement")
@Api(value = "swpmlongperiodsettlement", tags = "长周期结算日期参数表管理")
public class SwPmLongPeriodSettlementController {

    private final SwPmLongPeriodSettlementService swPmLongPeriodSettlementService;

    private final String ALL_LINE = "ALL";

    /**
     * 分页查询
     *
     * @param page                     分页对象
     * @param swPmLongPeriodSettlement 长周期结算日期参数表
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page")
    public R getSwPmLongPeriodSettlementPage(Page page, SwPmLongPeriodSettlement swPmLongPeriodSettlement) {
        return R.ok(swPmLongPeriodSettlementService.page(page, Wrappers.query(swPmLongPeriodSettlement)));
    }

    /**
     * 通过id查询长周期结算日期参数表
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}")
    public R getById(@PathVariable("id") Integer id) {
        return R.ok(swPmLongPeriodSettlementService.getById(id));
    }

    /**
     * 新增长周期结算日期参数表
     *
     * @param swPmLongPeriodSettlementDTO 长周期结算日期参数表
     * @return R
     */
    @ApiOperation(value = "新增长周期结算日期参数表", notes = "新增长周期结算日期参数表")
    @SysLog("新增长周期结算日期参数表")
    @PostMapping
    @PreAuthorize("@pms.hasPermission('support_sw_pm_long_period_settlement_add')")
    public R save(@RequestBody SwPmLongPeriodSettlementDTO swPmLongPeriodSettlementDTO) {
        SwPmLongPeriodSettlement defaultObj = ObjectUtils.getDefaultObj(SwPmLongPeriodSettlement.class);
        BeanUtils.copyProperties(swPmLongPeriodSettlementDTO, defaultObj);
        if (ALL_LINE.equals(defaultObj.getLineCode().toUpperCase())) {
            List<SwPmLongPeriodSettlement> list = swPmLongPeriodSettlementService.list(Wrappers.query(new SwPmLongPeriodSettlement()).lambda().
                    eq(SwPmLongPeriodSettlement::getLineCode, ALL_LINE));
            if (!list.isEmpty()) {
                return R.failed("已存在全线路结算日期，不能重复设置");
            }
        } else {
            List<SwPmLongPeriodSettlement> list = swPmLongPeriodSettlementService.list(Wrappers.query(new SwPmLongPeriodSettlement()).lambda().
                    eq(SwPmLongPeriodSettlement::getLineCode, defaultObj.getLineCode()).
                    eq(SwPmLongPeriodSettlement::getStationCode, defaultObj.getStationCode()));
            if (!list.isEmpty()) {
                return R.failed("已存在该站点的结算日期，不能重复设置");
            }
        }

		defaultObj.setTvmSettlementTerm(String.valueOf(defaultObj.getSettlementTerm()));
		defaultObj.setBomSettlementTerm(String.valueOf(defaultObj.getSettlementTerm()));
        PigxUser user = SecurityUtils.getUser();
        defaultObj.setOperationPersonName(user.getNikeName());
        defaultObj.setOperationPersonCode(user.getUserCode());
        defaultObj.setOperationTime(LocalDateTime.now());
        return R.ok(swPmLongPeriodSettlementService.save(defaultObj));
    }

    /**
     * 修改长周期结算日期参数表
     *
     * @param swPmLongPeriodSettlementDTO 长周期结算日期参数表
     * @return R
     */
    @ApiOperation(value = "修改长周期结算日期参数表", notes = "修改长周期结算日期参数表")
    @SysLog("修改长周期结算日期参数表")
    @PutMapping
    @PreAuthorize("@pms.hasPermission('support_sw_pm_long_period_settlement_edit')")
    public R updateById(@RequestBody SwPmLongPeriodSettlementDTO swPmLongPeriodSettlementDTO) {
        SwPmLongPeriodSettlement obj = new SwPmLongPeriodSettlement();
        BeanUtils.copyProperties(swPmLongPeriodSettlementDTO, obj);
		obj.setTvmSettlementTerm(String.valueOf(obj.getSettlementTerm()));
		obj.setBomSettlementTerm(String.valueOf(obj.getSettlementTerm()));
        return R.ok(swPmLongPeriodSettlementService.updateById(obj));
    }

    /**
     * 通过id删除长周期结算日期参数表
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除长周期结算日期参数表", notes = "通过id删除长周期结算日期参数表")
    @SysLog("通过id删除长周期结算日期参数表")
    @DeleteMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('support_sw_pm_long_period_settlement_del')")
    public R removeById(@PathVariable Integer id) {
        return R.ok(swPmLongPeriodSettlementService.removeById(id));
    }

    /**
     *查询列表
     *
     * @return
     */
    @ApiOperation(value = "列表查询", notes = "列表查询")
    @GetMapping("/findList/{stationCode}/{lineCode}")
    public R findList(@PathVariable("stationCode") String stationCode,@PathVariable("lineCode") String lineCode) {
        QueryWrapper<SwPmLongPeriodSettlement> queryWrapper = new QueryWrapper<SwPmLongPeriodSettlement>();
        queryWrapper.eq("delFlag",1);
        queryWrapper.eq("tvmStatus",1);
        queryWrapper.eq("bomStatus",1);
        List<SwPmLongPeriodSettlement> settlementList=swPmLongPeriodSettlementService.list(queryWrapper);
        for (SwPmLongPeriodSettlement swPmLongPeriodSettlement : settlementList) {
            if(swPmLongPeriodSettlement.getStationCode().equalsIgnoreCase(stationCode)){
                    return R.ok(swPmLongPeriodSettlement);
            }else{
                if(swPmLongPeriodSettlement.getLineCode().equalsIgnoreCase(lineCode)){
                        return R.ok(swPmLongPeriodSettlement);
                }else{
                    if(swPmLongPeriodSettlement.getLineCode().equalsIgnoreCase("ALL")){
                        return R.ok(swPmLongPeriodSettlement);
                    }
                }

            }

        }
        return R.ok("未设置结算周期");
    }

    /**
     * 批量修改长周期结算日期参数表
     *
     * @param
     * @return R
     */
    @ApiOperation(value = "批量修改长周期结算日期参数表", notes = "批量修改长周期结算日期参数表")
    @SysLog("批量修改长周期结算日期参数表")
    @PutMapping({"/updateBatchMany"})
    @ApiImplicitParams(
            {
                    @ApiImplicitParam(name = "lineCodes", value = "线路多选", dataTypeClass = String.class),
                    @ApiImplicitParam(name = "settlementTerm", value = "结算天数", dataTypeClass = String.class)
            }
    )
    public R updateBatchMany(String lineCodes,String settlementTerm) {
        if(StringUtils.isEmpty(lineCodes) || StringUtils.isEmpty(settlementTerm)){
            return R.failed("请检查线路和结算天数！");
        }
        try {
            PigxUser user = SecurityUtils.getUser();
            String[] split = lineCodes.split(",");
            UpdateWrapper<SwPmLongPeriodSettlement> objectUpdateWrapper = new UpdateWrapper<>();
            objectUpdateWrapper.in("LINE_CODE",split);
            objectUpdateWrapper.set("SETTLEMENT_TERM",Integer.valueOf(settlementTerm));
			objectUpdateWrapper.set("TVM_SETTLEMENT_TERM",settlementTerm);
			objectUpdateWrapper.set("BOM_SETTLEMENT_TERM",settlementTerm);
            objectUpdateWrapper.set("OPERATION_TIME",LocalDateTime.now());
            objectUpdateWrapper.set("OPERATION_PERSON_NAME",user.getNikeName());
            objectUpdateWrapper.set("OPERATION_PERSON_CODE",user.getUserCode());
            return R.ok(swPmLongPeriodSettlementService.update(objectUpdateWrapper));
        } catch (Exception e) {
            e.printStackTrace();
            return R.failed("请检查线路和结算天数！");
        }
    }
}
